package com.nulldev.util.io.extensions.nstream.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.nulldev.util.data.longNumbers.lNumber;
import com.nulldev.util.io.IOUtils;
import com.nulldev.util.io.extensions.nstream.nStream;

public class InputStreams implements nStream {

	private InputStream input;
	private OutputStream output;

	@Override
	public boolean readable() {
		return this.input != null;
	}

	@Override
	public boolean writeable() {
		return this.output != null;
	}

	@Override
	public void sync() throws IOException {
		if (this.output != null)
			this.output.flush();
	}

	@Override
	public void close() throws IOException {
		IOUtils.closeQuietly(this.input);
		IOUtils.closeQuietly(this.output);
	}

	@Override
	public byte[] next(final int bytes) throws IOException {
		if (this.input == null)
			throw new UnsupportedOperationException("Reading on this stream is not supported!");
		if (bytes < 0)
			throw new IllegalArgumentException("bytes < 0!");
		final byte[] f = new byte[bytes];
		IOUtils.readFully(this.input, f, 0, bytes);
		return f;
	}

	@Override
	public int next() throws IOException {
		if (this.input == null)
			throw new UnsupportedOperationException("Reading on this stream is not supported!");
		return this.input.read();
	}

	@Override
	public int at(final int position) throws IOException {
		throw new UnsupportedOperationException("Positional streams are not supported!");
	}

	@Override
	public int positionLegacy() {
		throw new UnsupportedOperationException("Positional streams are not supported!");
	}

	@Override
	public lNumber position() {
		throw new UnsupportedOperationException("Positional streams are not supported!");
	}

	@Override
	public void reset() throws IOException, UnsupportedOperationException {
		if (this.input != null)
			this.input.reset();
	}

	@Override
	public void write(final int _byte) throws IOException {
		if (this.output != null)
			this.output.write(_byte);
	}

	@Override
	public void write(final byte[] data) throws IOException {
		if (this.output != null)
			this.output.write(data);
	}

}
